﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CdcBusiness;
using PdfSharp.Pdf;
using System.IO;
using DAO.Cdc;
using Business.Cdc;

namespace Cdc
{
    /// <summary>
    /// Interaction logic for Import.xaml
    /// </summary>
    public partial class Import : Manageo.INotifierUI
    {
        private PdfDocument pdfDoc = null;

        System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
        public Import()
        {
            InitializeComponent();
            bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
        }

        void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            loadFiles((string)e.Argument);
        }

        public void loadFiles(String pathCsv)
        {

            FileStream inStream = new FileStream(pathCsv, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            MemoryStream storeStream = new MemoryStream();

            storeStream.SetLength(inStream.Length);
            inStream.Read(storeStream.GetBuffer(), 0, (int)inStream.Length);
            storeStream.Flush();
            inStream.Close();
            StreamReader rdr = new StreamReader(storeStream, System.Text.Encoding.Default);

            int i = 0;
            while (!rdr.EndOfStream)
            {
                rdr.ReadLine();
                i++;
            }
            double lineNumbers = i-1;

            OnBegin(null);

            string line, path, title, subject, from = null, to = null;
            DateTime date;
            Stream fs = null;
            Boolean reported;
            rdr.BaseStream.Position = 0;
            // on supprime les headers !
            if (!rdr.EndOfStream)
            {
                line = rdr.ReadLine();
            }
            i = 0;
            int value;
            // on lit les données
            FileDb file = null;
            while (!rdr.EndOfStream)
            {
                line = rdr.ReadLine();
                string[] data = line.Split(';');
                path = data[0];
                title = data[1];
                subject = data[2];
                date = DateTime.Parse(data[3]);
                reported = "1".Equals(data[4]);
                file = new FileDb();
                if (data.Length > 5)
                {
                    from = data[5];
                    to = data[6];
                }
                if (String.IsNullOrEmpty(from) && String.IsNullOrEmpty(to))
                {
                    fs = new FileStream(path, FileMode.Open);
                }
                else
                {
                    PdfDocument pdfDoc = PdfDocumentGenerator.selectFile(path);
                    pdfDoc = PdfDocumentGenerator.getFile(pdfDoc, Int32.Parse(from), Int32.Parse(to));
                    fs = new MemoryStream();
                    pdfDoc.Save(fs, false);
                }

                file.Reported = reported;
                file.Date = date;
                file.Subject = subject;
                file.Title = title;
                CdcFilesDAO.InsertData(fs, file);
                value = (int)(((++i) / lineNumbers) * 100.0);
                OnChanged(new Manageo.NotifyEventArgs(value, "import des fichiers en cours..."));
            }

            OnEnded(null);
        }

        private void import(object sender, RoutedEventArgs e)
        {
            pdfDoc = PdfDocumentGenerator.getFile(pdfDoc, (int)FromTb.Value, (int)ToTb.Value);
            FileDb file = new FileDb();
            file.Title=TitleTb.Text;
            file.Subject=SubjectCb.Text;
            file.Date = dateCh.DateTime;
            file.Reported = true;
            MemoryStream ms = new MemoryStream();
            pdfDoc.Save(ms);
            CdcFilesDAO.InsertData(ms, file);
        }

        private void selectFile(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".pdf";
            dlg.Filter = "PDF documents (.pdf)|*.pdf";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                FilePathTb.Text = filename;
                pdfDoc = PdfDocumentGenerator.selectFile(filename);
                this.FromTb.IsEnabled = true;
                this.ToTb.IsEnabled = true;
                this.FromTb.MaxValue = pdfDoc.PageCount;
                this.ToTb.MaxValue = pdfDoc.PageCount;
                this.ToTb.Value = pdfDoc.PageCount+1;
                this.FromTb.Value = 1;
            }
        }

        private void loadFiles(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".csv";
            dlg.Filter = "CSV documents (.csv)|*.csv";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true && !String.IsNullOrEmpty(dlg.FileName))
            {
                bw.RunWorkerAsync(dlg.FileName);
            }
        }
    }
}
